//
//  YBCloudComputerDetailVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/8.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import SwiftyJSON

class YBCloudComputerDetailVC: BaseVC {
    
    enum SectionType {
        case open
        case progress
        case detail
        case basicFunc([BasicFunc])
        
        enum BasicFunc: Int {
            case restartPhone
            case activationCodeRecharge
            case rechargeAndRenewal
            case pointConversion
            
            var style: (icon: String, title: String, des: String) {
                switch self {
                case .restartPhone: return ("icon_cloudcomputer_restart", "重启手机", "重启云手机解决卡死问题")
                case .activationCodeRecharge: return ("icon_cloudcomputer_activationcode", "激活码充值", "使用激活码延长设备时长")
                case .rechargeAndRenewal: return ("icon_cloudcomputer_recharge", "充值续费", "续费继续使用当前云手机")
                case .pointConversion: return ("icon_cloudcomputer_point", "积分兑换", "使用积分延长使用时间")
                }
            }
        }
    }
    
    //    private let sections: [SectionType] = [.open, .progress, .detail, .basicFunc([.restartPhone, .activationCodeRecharge, .rechargeAndRenewal, .pointConversion])]
    private let sections: [SectionType] = [.open, .progress, .detail, .basicFunc([.restartPhone])]
    private let kModel: YBUserModel.OrderInfoVos
    private let kPairModel: YBPairModel
    private var hasRevicedSSEReback = false
    private var hasRevicedReback = false
    
    // 处理添加逻辑的
    lazy var pcVC: MainFrameViewController = {
        let pcVC = MainFrameViewController()
        pcVC.deleagte = self
        pcVC.superController = self
        return pcVC
    }()
    
    init(model: YBUserModel.OrderInfoVos, pairModel: YBPairModel) {
        kModel = model
        kPairModel = pairModel
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // 结束SSE链接
        YBSSEManager.sharedInstance().func__endWithEventSource()
        
        self.hasRevicedReback = false
        self.hasRevicedSSEReback = false
        
        // 停止计时器
        TaskTool.cancelTimer()
        
        // 触发其他的
        self.pcVC.viewDidDisappear(true)
    }
    
    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigation.item.title = kModel.productName
        navigation.item.rightBarButtonItem = UIBarButtonItem(customView: newsBtn)
        view.backgroundColor = .lightGray242Dark17
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 开始链接SSE
        YBSSEManager.sharedInstance().func__startWithEventSource()
        addNoc()
        startOpenPC()
    }
    
    // 获取条Cell
    func progressCell() -> YBCloudComputerProgressCell? {
        let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 1))
        if cell is YBCloudComputerProgressCell {
            return cell as? YBCloudComputerProgressCell
        }
        return nil
    }
    
    fileprivate func addNoc() {
        NotificationCenter.default.addObserver(self, selector: #selector(powerOnSuccess), name: .didPowerOnSuccess, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(powerOffSuccess), name: .didPowerOffSuccess, object: nil)
    }
    
    // 开机成功的通知
    @objc func powerOnSuccess() {
        self.hasRevicedSSEReback = true
        DispatchQueue.main.async { [self] in
            // 开始添加PC
            TaskTool.delay(1) { [self] in
                let wtpcportArr = kPairModel.wtpcport.components(separatedBy: "#")
                self.addPC(port: wtpcportArr[1])
            }
        }
    }
    
    // 关机成功的通知
    @objc func powerOffSuccess() {
        // 结束SSE
        YBSSEManager.sharedInstance().func__endWithEventSource()
    }
    
    // 开始添加PC
    func addPC(port: String) {
        DispatchQueue.main.async {
            self.pcVC.power(on: self.kPairModel.wip + ":" + port, vnName: self.kPairModel.vmName, isSunshine: self.kModel._isSunshine) { [weak self] success, msg in
                // 停止计时器
                TaskTool.cancelTimer()
                
                if success {
                    // 处理cell 上的UI更新
                    DispatchQueue.main.async {
                        self?.progressCell()?.progress = .done
                        self?.hasRevicedReback = true
                    }
                    
                }else {
                    // 重试
                    DispatchQueue.main.async {
                        self?.progressCell()?.refreshTitle(msg ?? "开机失败")
                        self?.progressCell()?.progress = .fail
                    }
                }
            }
        }
    }
    
    // 开机进度
    func startOpenPC() {
        var current = 0.0
        // 进度条更新
        TaskTool.dispatchTimer(timeInterval: 0.1, repeatCount: 5 * 600) { [self] timer, count in
            if count == 600 {
                // 检查是否收到了SSE通知
                if !self.hasRevicedSSEReback {
                    // 请求接口
                    self.checkSSE()
                }
            }else if count == 10 {
                // 1分钟后还没收到链接成功的通知
                if !self.hasRevicedReback {
                    DispatchQueue.main.async {
                        self.progressCell()?.refreshTitle("用户资源加载失败，请重试")
                        self.progressCell()?.progress = .fail
                    }
                }
            }else {
                current += 0.01
                DispatchQueue.main.async {
                    self.progressCell()?.refreshProgress(progress: current)
                }
            }
        }
    }
    
    // 检查SSE链接
    func checkSSE() {
        vm.req_CheckSSEForPC(kPairModel.vmName) { ok, obj, msg, code in
            // 停止计时器
            TaskTool.cancelTimer()
            DispatchQueue.main.async {
                if ok {
                    guard let js = obj as? JSON else { return }
                    let success = js["success"].boolValue
                    if success {
                        // 处理cell 上的UI更新
                        self.progressCell()?.progress = .done
                    }else {
                        self.progressCell()?.refreshTitle("用户资源加载失败，请联系管理员")
                        self.progressCell()?.progress = .fail
                    }
                }else {
                    self.progressCell()?.refreshTitle(msg ?? "请求失败")
                    self.progressCell()?.progress = .fail
                }
            }
        }
    }
    
    // MARK: - lazy
    lazy var vm: YBCloudComputerViewModel = {
        let vm = YBCloudComputerViewModel()
        return vm
    }()
    
    private lazy var tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .grouped)
        tv.estimatedRowHeight = 44
        tv.rowHeight = UITableView.automaticDimension
        tv.delegate = self
        tv.dataSource = self
        tv.separatorStyle = .none
        tv.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tv.sectionHeaderTopPadding = 0
        }
        tv.register(headerFooterViewClassWith: YBCloudComputerTableSecHeader.self)
        tv.register(cellWithClass: YBCloudComputerOpenCell.self)
        tv.register(cellWithClass: YBCloudComputerProgressCell.self)
        tv.register(cellWithClass: YBCloudComputerDetailCell.self)
        tv.register(cellWithClass: YBCloudComputerBasicFuncCell.self)
        return tv
    }()
    
    private lazy var newsBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "icon_cloudcomputer_news"), for: .normal)
        btn.bk_addTarget { sender in
            let messageVC = YBMessageVC()
            self.navigationController?.pushViewController(messageVC, animated: true)
        }
        return btn
    }()
    
}


// MARK: - UITableView代理
extension YBCloudComputerDetailVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sec = sections[section]
        switch sec {
        case .open, .progress, .detail:
            return UIView()
        case .basicFunc:
            let header = tableView.dequeueReusableHeaderFooterView(withClass: YBCloudComputerTableSecHeader.self)
            header.kTitleLabel.text = "基础功能"
            return header
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let sec = sections[section]
        switch sec {
        case .open, .progress, .detail: return 0.01
        case .basicFunc: return 36
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sec = sections[section]
        switch sec {
        case .open, .progress, .detail: return 1
        case .basicFunc(let rows): return rows.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sec = sections[indexPath.section]
        switch sec {
        case .open:
            let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerOpenCell.self, for: indexPath)
            return cell
        case .progress:
            let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerProgressCell.self, for: indexPath)
            // 进入操作
            cell.powerOnBlock = {
                self.pcVC.startPC()
            }
            
            // 重试
            cell.reTryBlock = {
                self.navigationController?.popViewController(animated: true)
            }
            
            // 关机操作
            cell.powerOffBlock = { [self] in
                self.closePC(message: "您确定要退出当前设备？所有未保存的数据将丢失。", sureTitle: "关机")
            }
            return cell
        case .detail:
            let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerDetailCell.self, for: indexPath)
            cell.updateCell(by: kModel)
            return cell
        case .basicFunc(let rows):
            let row = rows[indexPath.row]
            let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerBasicFuncCell.self, for: indexPath)
            cell.updateCell(by: row)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sec = sections[indexPath.section]
        switch sec {
        case .open:
            break
        case .progress:
            break
        case .detail:
            break
        case .basicFunc(let rows):
            let row = rows[indexPath.row]
            switch row {
            case .restartPhone:
                self.closePC(message: "您确定要重启当前设备？所有未保存的数据将丢失。", sureTitle: "重启")
                break
            case .activationCodeRecharge:
                let vc = YBMineActivationCodeVC()
                self.navigationController?.pushViewController(vc)
                break
            case .rechargeAndRenewal:
                break
            case .pointConversion:
                break
            }
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let shapeLayer = CAShapeLayer()
        cell.layer.mask = nil
        let sec = sections[indexPath.section]
        switch sec {
        case .open, .detail:
            let bezierPath = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 4, height: 4))
            shapeLayer.path = bezierPath.cgPath
            cell.layer.mask = shapeLayer
            
        case .basicFunc(let rows):
            let row = rows[indexPath.row]
            guard row == .pointConversion else { return }
            let bezierPath = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 4, height: 4))
            shapeLayer.path = bezierPath.cgPath
            cell.layer.mask = shapeLayer
            
        case .progress:
            // 不绘制
            break
        }
        
    }
    
    /// 关机
    func closePC(message: String, sureTitle: String) {
        let alertController = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: sureTitle, style: .default) { [self] _ in
            // 发送关机指令
            vm.req_ClosePC { ok, obj, msg, code in
                if ok {
                    print("关机成功")
                }
            }
            self.navigationController?.popViewController(animated: true)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        
        // 在当前视图控制器中呈现提示框
        if let viewController = UIApplication.shared.delegate?.window??.rootViewController {
            viewController.present(alertController, animated: true, completion: nil)
        }
    }
}


// MARK: - MainFrameViewControllerDelegate
extension YBCloudComputerDetailVC: MainFrameViewControllerDelegate {
    
    func pairFailed(_ message: String!) {
        // 创建一个 UIAlertController 对象
        let alertController = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        
        // 创建一个确定按钮
        let okAction = UIAlertAction(title: "确定", style: .default) { [self] _ in
            // 发送关机指令
            vm.req_ClosePC { ok, obj, msg, code in
                if ok {
                    print("关机成功")
                }
            }
            self.navigationController?.popViewController(animated: true)
        }
        
        // 创建一个取消按钮
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
            // 当用户点击取消按钮时执行的操作
            print("用户点击了取消按钮")
        }
        
        // 将确定按钮添加到提示框中
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        
        DispatchQueue.main.async {
            // 在当前视图控制器中呈现提示框
            if let viewController = UIApplication.shared.delegate?.window??.rootViewController {
                viewController.present(alertController, animated: true, completion: nil)
            }
        }
    }
    
    /// 准备配对
    func readyPin(_ pin: String!) {
        let params = ["password": "acX@13.",
                      "pin": pin ?? "",
                      "userName": "cmp",
                      "vmName": kPairModel.vmName]
        vm.req_Pair(params) { ok, obj, msg, code in
            HintTool.toast(msg)
            if !ok {
                // 失败了
                DispatchQueue.main.async {
                    self.progressCell()?.refreshTitle(msg ?? "配对请求失败")
                    self.progressCell()?.progress = .fail
                }
            }
        }
    }
    
}
